package com.example.bookappgraduation.fragments;

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.toolbox.StringRequest;
import com.example.bookappgraduation.R;
import com.example.bookappgraduation.adapters.CategoryAdapter;
import com.example.bookappgraduation.models.Category;
import com.example.bookappgraduation.utils.VolleySingleton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;

public class CategoriesFragment extends Fragment {

    private RecyclerView recyclerViewCategories;
    private CategoryAdapter categoryAdapter;
    private List<Category> categoryList;
    private ProgressBar progressBar;
    private  String API_KEY;

    public CategoriesFragment() { /* Required empty public constructor */ }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        API_KEY = getString(R.string.juhe_api_key); // 初始化 API_KEY
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_categories, container, false);

        recyclerViewCategories = view.findViewById(R.id.recyclerViewCategories);
        progressBar = view.findViewById(R.id.progressBarCategories);
        recyclerViewCategories.setLayoutManager(new LinearLayoutManager(getContext()));
        categoryList = new ArrayList<>();
        categoryAdapter = new CategoryAdapter(getContext(), categoryList);
        recyclerViewCategories.setAdapter(categoryAdapter);

        fetchCategories();

        return view;
    }

    private void fetchCategories() {
        progressBar.setVisibility(View.VISIBLE);
        String url = "http://apis.juhe.cn/goodbook/catalog?key=" + API_KEY;

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                response -> {
                    progressBar.setVisibility(View.GONE);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        if (jsonObject.getInt("error_code") == 0) {
                            JSONArray resultArray = jsonObject.getJSONArray("result");
                            categoryList.clear(); // 清空旧数据
                            for (int i = 0; i < resultArray.length(); i++) {
                                JSONObject categoryObject = resultArray.getJSONObject(i);
                                String id = categoryObject.getString("id");
                                String catalogName = categoryObject.getString("catalog");
                                categoryList.add(new Category(id, catalogName));
                            }
                            categoryAdapter.notifyDataSetChanged();
                        } else {
                            Toast.makeText(getContext(), "获取分类失败: " + jsonObject.getString("reason"), Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(getContext(), "JSON 解析错误", Toast.LENGTH_SHORT).show();
                    }
                },
                error -> {
                    progressBar.setVisibility(View.GONE);
                    Log.e("CategoriesFragment", "Volley Error: " + error.toString());
                    Toast.makeText(getContext(), "网络错误，请稍后重试", Toast.LENGTH_SHORT).show();
                });

        VolleySingleton.getInstance(getContext()).addToRequestQueue(stringRequest);
    }
}